﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using SpectationClient;
using SpectationClient.GUI;
//using SpectationClient.GUI.UC;
using SpectationClient.Stuff;
using SpectationClient.SQLCommandBuilder;
using SpectationClient.DataBaseDescription;
using SpectationClient.Async;

using System.IO;
//using SharpMap.Geometries;
//using SharpMap.Converters.WellKnownText;
//using ProjNet.CoordinateSystems;
//using ProjNet.CoordinateSystems;
using Npgsql;


namespace SpectationClient.GUI {
    public partial class SubSearch : Form {
        private const String CNMP_ID_VAL = "ID_VAL";
        private const String CNMP_DISP = "Beschreibung";
        private const String CNMP_TT = "TOOLTIP";
        private const String CNMP_ID_NAME = "ID";
        private const String C_RTF_CMDERROR = "Bitte Auswahlkriterien korrekt definieren";
        private System.Text.RegularExpressions.Regex REGEX_ENDDOTS = new System.Text.RegularExpressions.Regex("[.]+$"
                                                                        ,System.Text.RegularExpressions.RegexOptions.Singleline);
        private AGetDatabaseObject AGDBO;
        private DataBaseInfo DBINFO;

        private UC_CoordinateSystem LOC_BUFFER_UC;
        private UC_ParseNumbers CORE_ID_UC;
        private ErrorList EL; 
        private NpgsqlCommand search_cmd;

        private bool SQL_INIT_CORRECT = true;
        private Dictionary<Object, Control> initLUTComboBoxes = new Dictionary<Object, Control>();
        private int sql_init_tables = 0;
        
        private DBManager DBM = null;
        
        public SubSearch(ref DBManager dbm) {
            InitializeComponent();


            this.Icon = Resources.Icon;
            this.DBM = dbm;
            this.DBINFO = dbm.getDataBaseInfo();
            this.AGDBO = new AGetDatabaseObject();
            this.AGDBO.GetDataTableCompleted +=new GetDataTableCompletedEventHandler(AGDBO_GetDataTableCompleted);
            this.AGDBO.ProgressChanged +=new Async.ProgressChangedEventHandler(AGDBO_ProgressChanged);
            this.EL = new ErrorList();
            this.EL.ErrorAdded += new EventHandler(EL_ErrorAdded);
            this.EL.ErrorListIsEmpty += new EventHandler(EL_ErrorListIsEmpty);
            this.FormClosing += new FormClosingEventHandler(SubSearch_FormClosing);
            this.timer.Tick += new EventHandler(timer_Tick);
            this.tsl_Message.Text = "";
            initCBoxes();
            initDGVs();
            initValidators();

        }

        void AGDBO_ProgressChanged(object sender, ProgressChangedEventArgs e) {
            throw new NotImplementedException();
        }

        void AGDBO_GetDataTableCompleted(object sender, GetDataTableCompletedEventArgs e) {
            Object key = e.UserState;
           
            if(e.Cancelled) {

            } else if(e.Error != null) {
                this.SQL_INIT_CORRECT = false;
                this.RTB_CMD.Text += TextHelper.Exception2String(e.Error);
            } else {
                Object o = this.initLUTComboBoxes[key];

                if(key is TableInfo) {
                    TableInfo ti = key as TableInfo;
                    if(o is CheckedListBox) {
                        CheckedListBox clb = o as CheckedListBox;
                        FormHelper.initCheckedListBox(clb, e.DataTable, ti);
                    } else if(o is ComboBox) {
                        ComboBox cb = o as ComboBox;
                        FormHelper.initComboBoxItems(cb, e.DataTable, ti, true);
                    }
                } else if(key is String) {
                    e.DataTable.Rows.InsertAt(e.DataTable.NewRow(), 0);
                    
                    ComboBox cb = o as ComboBox;
                    String member =  e.DataTable.Columns[0].ColumnName;
                    FormHelper.initComboBoxItems(cb, e.DataTable, member, member);
                }
            }
            this.initLUTComboBoxes.Remove(key);

            this.tsl_ProgressBar.Value = sql_init_tables - initLUTComboBoxes.Count;
            if(this.initLUTComboBoxes.Count == 0) {
                this.timer.Stop();
                if(this.SQL_INIT_CORRECT) {
                    this.tsl_Message.Text = "Initialisierung abgeschlossen";
                } else {
                    this.tsl_Message.Text = "Initialisierung fehlgeschlagen";
                }
                this.tsl_ProgressBar.Value = 0;
            } 
        }

        void SubSearch_FormClosing(object sender, FormClosingEventArgs e) {
            AGDBO.CancelAllRequest();
        }

        void timer_Tick(object sender, EventArgs e) {
            String txt = this.tsl_Message.Text;
            if(txt != null) {
                System.Text.RegularExpressions.Match m = this.REGEX_ENDDOTS.Match(txt);
                if(m.Length < 3) {
                    tsl_Message.Text += '.';
                } else {
                    tsl_Message.Text = txt.Remove(txt.Length - 3);
                }
            }
        }

       
       
        private void initDGVs() {
            int minHeight = 10;
            int maxHeight = 250;

            FormHelper.setFlexibleHeight(VGFZ_SP_DGV, minHeight, maxHeight);
            VGFZ_SP_DGV.DataSource = DBM.getEmptyTable("CKEYS", "GE_ARTEN_BUNDESLISTE");
            VGFZ_SP_DGV.RowsAdded += new DataGridViewRowsAddedEventHandler(DGV_RowAddedEventPrepareCommand);
            VGFZ_SP_DGV.RowsRemoved += new DataGridViewRowsRemovedEventHandler(DGV_RowRemoveEventPrepareCommand);
            
            FormHelper.setFlexibleHeight(VGFZ_PS_BB_DGV, minHeight, maxHeight);
            VGFZ_PS_BB_DGV.DataSource = DBM.getEmptyTable("CKEYS", "GE_BIOTOPTYP_BB");
            VGFZ_PS_BB_DGV.RowsAdded += new DataGridViewRowsAddedEventHandler(DGV_RowAddedEventPrepareCommand);
            VGFZ_PS_BB_DGV.RowsRemoved += new DataGridViewRowsRemovedEventHandler(DGV_RowRemoveEventPrepareCommand);

            FormHelper.setFlexibleHeight(VGFZ_PS_BfN_DGV, minHeight, maxHeight);
            //VGFZ_PS_BfN_DGV.DataSource = DBM.getEmptyTable("CKEYS", "GE_BIOTOPTYP_BB");
            VGFZ_PS_BfN_DGV.RowsAdded += new DataGridViewRowsAddedEventHandler(DGV_RowAddedEventPrepareCommand);
            VGFZ_PS_BfN_DGV.RowsRemoved += new DataGridViewRowsRemovedEventHandler(DGV_RowRemoveEventPrepareCommand);


            FormHelper.setFlexibleHeight(VGFZ_PS_EUNIS_DGV, minHeight, maxHeight);
            VGFZ_PS_EUNIS_DGV.DataSource = DBM.getEmptyTable("CKEYS", "EUNIS_HABITATS");
            VGFZ_PS_EUNIS_DGV.RowsAdded += new DataGridViewRowsAddedEventHandler(DGV_RowAddedEventPrepareCommand);
            VGFZ_PS_EUNIS_DGV.RowsRemoved += new DataGridViewRowsRemovedEventHandler(DGV_RowRemoveEventPrepareCommand);

            FormHelper.setFlexibleHeight(OBSAREA_DGV, minHeight, maxHeight);
            OBSAREA_DGV.DataSource = DBM.getEmptyTable("C_GFZ", "VIEW_OBSERVATION_AREAS");
            OBSAREA_DGV.RowsAdded += new DataGridViewRowsAddedEventHandler(DGV_RowAddedEventPrepareCommand);
            OBSAREA_DGV.RowsRemoved += new DataGridViewRowsRemovedEventHandler(DGV_RowRemoveEventPrepareCommand);
            //TEST

            
        }

        void DGV_RowAddedEventPrepareCommand(object sender, DataGridViewRowsAddedEventArgs e) {
            Val_Required(null, null);
        }

        void DGV_RowRemoveEventPrepareCommand(object sender, DataGridViewRowsRemovedEventArgs e) {
            Val_Required(null, null);
        }

        

        private void initCBoxes() {
            this.SEARCH_bt.Enabled = false;
            this.timer.Start();
            this.tsl_Message.Text = "Initialisiere Datenbankinformationen";


            //Link Buttons...
            //Checkboxes
            FormHelper.setLinkAction_SwitchVisualization(gb_CORE_CAMPAIGN_USER_cb, gb_CORE_CAMPAIGN_USER);
            FormHelper.setLinkAction_SwitchVisualization(gb_CORE_LOCATIONS_cb, gb_CORE_LOCATION);
            FormHelper.setLinkAction_SwitchVisualization(gb_CORE_SENSORS_WREF_cb, gb_CORE_SENSORS_WREF);
            FormHelper.setLinkAction_SwitchVisualization(gb_CORE_SPECTRA_cb, gb_CORE_SPECTRA);
            FormHelper.setLinkAction_SwitchVisualization(gb_CGFZ_OBSAREA_cb, gb_CGFZ_OBSAREA);
            FormHelper.setLinkAction_SwitchVisualization(gb_CGFZ_PS_cb, gb_CGFZ_PS);
            FormHelper.setLinkAction_SwitchVisualization(gb_CGFZ_SP_cb, gb_CGFZ_SP);


            CORE_ID_UC = new UC_ParseNumbers();
            CORE_ID_UC.LabelsChanged += new EventHandler(Val_Required);
            CORE_ID_PANEL.Controls.Add(CORE_ID_UC);

            //Default Coordinate System
            int srid = ((ColumnInfoGeometry)DBM.getColumnInfo("CORE", "LOCATIONS", "SHAPE")).SRID;
            LOC_BUFFER_UC = new UC_CoordinateSystem(ref DBM, srid);
            LOC_BUFFER_UC.LabelsChanged += new EventHandler(LOC_BUFFER_UC_LabelsChanged);
            LOC_BUFF_CSPanel.Controls.Add(LOC_BUFFER_UC);
            LOC_label_LAT_Y.Text     = LOC_BUFFER_UC.COORD_LABEL_LATY;
            LOC_label_LONG_X.Text    = LOC_BUFFER_UC.COORD_LABEL_LONGX;

            //CORE Source
            //initCBOX_Items(ref CORE_Source, DBM.getColumnInfo("CORE", "SPECTRA", "source").possibleValues);
            
            FormHelper.initComboBoxItems(CORE_Source, DBM.getColumnInfo("CORE", "SPECTRA", "source").possibleValues, true);
            FormHelper.initComboBoxItems(CORE_SpecType, DBM.getColumnInfo("CORE", "SPECTRA", "spectype").possibleValues, true);
            

            
            //init LookupTables
            DataBaseInfo DBI = this.DBINFO;
            this.initLUTComboBoxes.Add(DBI["CORE"]["SENSORS"], gb_CORE_SENS_clb);
            this.initLUTComboBoxes.Add(DBI["CORE"]["WREF_PANELS"], gb_CORE_WREF_PANELS_clb);
            this.initLUTComboBoxes.Add(DBI["CORE"]["CAMPAIGNS"], gb_CORE_CAMP_clb);
            this.initLUTComboBoxes.Add(DBI["CORE"]["OPERATORS"], gb_CORE_USER_clb);

            TableInfo spectra = DBI["CORE"]["SPECTRA"];
            this.initLUTComboBoxes.Add("SELECT DISTINCT datatype FROM " + spectra.SchemaTableName, CORE_Datatype);
          
            this.sql_init_tables = this.initLUTComboBoxes.Count;
            foreach(Object o in this.initLUTComboBoxes.Keys) {
                NpgsqlCommand cmdSelect = null;
                if(o is TableInfo) {
                    TableInfo ti = o as TableInfo;
                    cmdSelect = CommandBuilder.getSELECT(ti);
                } else if(o is String) {
                    cmdSelect = new NpgsqlCommand((o as String));
                }
                cmdSelect.Connection = this.DBM.Connection;
                this.AGDBO.GetDataTableAsync(cmdSelect, o);
            }
         
            
        }



        void LOC_BUFFER_UC_LabelsChanged(object sender, EventArgs e) {
            LOC_label_LAT_Y.Text = LOC_BUFFER_UC.COORD_LABEL_LATY;
            LOC_label_LONG_X.Text = LOC_BUFFER_UC.COORD_LABEL_LONGX;
        }

      

        #region Prepare DataBase Commands Searching For Spectrum-spectraIDs
        
        /// <summary>
        /// Create the DataBase-SQL-Command
        /// </summary>
        private void Val_Required(object sender, EventArgs e) {
            try{
                if(this.SQL_INIT_CORRECT) {

                    ConditionList spec_constraints = new ConditionList(ConditionList.Op.AND);
                    spec_constraints.Add(sub_CORE2());



                    SetCondition spec_id_intersection = new SetCondition("id", SetCondition.Op.IN_INTERSECTION);
                    spec_id_intersection.Add(sub_LOCATION2());
                    spec_id_intersection.Add(sub_VEG_PS2());
                    spec_id_intersection.Add(sub_VEG_SP2());
                    spec_id_intersection.Add(sub_OBSAREAS2());
                    spec_id_intersection.Add(sub_WREF_PANELS2());

                    spec_constraints.Add(spec_id_intersection);

                    if(!spec_constraints.IsEmpty) {
                        TableInfo ti_spec = this.DBM.getTableInfo("CORE", "SPECTRA");
                        NpgsqlCommand cmd = new NpgsqlCommand(
                            String.Format("SELECT * FROM {0} WHERE ", ti_spec.SchemaTableName), this.DBM.Connection);
                        SQLCommandBuilder.CommandBuilder.appendCmd(ref cmd, spec_constraints.getCmd());
                        this.search_cmd = cmd;
                        String test = SQLCommandBuilder.CommandBuilder.CommandToString(cmd);
                        this.RTB_CMD.Text = test;
                        SEARCH_bt.Enabled = true;
                    } else {
                        this.search_cmd = null;
                        SEARCH_bt.Enabled = false;
                        this.RTB_CMD.Text = "Bitte Suchkriterien angeben";
                    }


                } else {
                    this.RTB_CMD.Text = "Warte auf Ergebnis einer SQL-Anfrage...";
                }
            }catch(Exception ex) {
                    RTB_CMD.Text = "";
                    SEARCH_bt.Enabled = false;
                    MessageBox.Show(TextHelper.Exception2String(ex), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                
            }
        }

      

        private ConditionList sub_CORE2() {
            ConditionList cl = new ConditionList(ConditionList.Op.AND);
            cl.Add(new Condition("datatype", Condition.Op.EQ, CORE_Datatype.SelectedValue));
            cl.Add(new Condition("source", Condition.Op.EQ, CORE_Source.SelectedValue));
            cl.Add(new Condition("spectype", Condition.Op.EQ, CORE_SpecType.SelectedValue));
            if(CORE_Date_Begin.Checked) cl.Add(new Condition("date", Condition.Op.GE, CORE_Date_Begin.Value.Date));
            if(CORE_Date_End.Checked) cl.Add(new Condition("date", Condition.Op.LE, CORE_Date_End.Value.Date));
            
            if(CORE_ID_UC.hasNumbers) {
                Condition c = new Condition("id", Condition.Op.EQ);
                foreach(long id in CORE_ID_UC.Numbers){
                    c.Add(id);
                };
                cl.Add(c);
            }

            Condition cOPERATOR = new Condition("id_operator", Condition.Op.EQ);
            foreach(Object o in gb_CORE_USER_clb.CheckedItems) {
                if(o is BoxItem) {
                    cOPERATOR.Add(((BoxItem)o).Value);
                } else {
                    throw new Exception("Case not implemented");
                }
            }
            cl.Add(cOPERATOR);

            Condition cCAMP = new Condition("id_campaign", Condition.Op.EQ);
            foreach(Object o in gb_CORE_CAMP_clb.CheckedItems) {
                if(o is BoxItem) {
                    cCAMP.Add(((BoxItem)o).Value);
                } else {
                    throw new Exception("Case not implemented");
                }
            }
            cl.Add(cCAMP);

            Condition cSENSOR = new Condition("id_sensor", Condition.Op.EQ);
            foreach(Object o in gb_CORE_SENS_clb.CheckedItems) {
                if(o is BoxItem) {
                    cSENSOR.Add(((BoxItem)o).Value);
                } else {
                    throw new Exception("Case not implemented");
                }
            }
            cl.Add(cSENSOR);
            return cl;
        
        }

       
        private NpgsqlCommand sub_WREF_PANELS2() {
            NpgsqlCommand cmd = null;
            if(gb_CORE_WREF_PANELS_clb.CheckedItems.Count > 0) {
                cmd = new NpgsqlCommand();
                TableInfo ti_view = this.DBM.getTableInfo("CORE", "VIEW_SPEC2WREF_PANELS");

                Condition c = new Condition("id_wref_panel", Condition.Op.EQ);
                foreach(Object o in gb_CORE_WREF_PANELS_clb.CheckedItems) {
                    if(o is BoxItem) {
                        c.Add(((BoxItem)o).Value);
                    }else{
                        throw new Exception("Case not implemented");
                    }
                }
                cmd = c.getCmd("panel");
                cmd.CommandText = String.Format("SELECT id_spectrum as id FROM {0} WHERE {1}",
                        ti_view.SchemaTableName, cmd.CommandText);
            }
            return cmd;
        }

        private NpgsqlCommand sub_VEG_SP2() {
            TableInfo tiSP = DBM.getTableInfo("C_GFZ", "VIEW_SPEC2PLANTS");
            NpgsqlCommand cmd = null;
            if(VGFZ_SP_DGV.Rows.Count > 0) {
                Condition c = new Condition("id_species", Condition.Op.EQ);
                int nPlants = VGFZ_SP_DGV.RowCount;

                foreach(DataGridViewRow row in VGFZ_SP_DGV.Rows) {
                    c.Add(row.Cells["id"].Value);
                }

                cmd = c.getCmd("myP");

                if(VGFZ_SP_musthaveall.Checked) {
                    cmd.CommandText = 
                      String.Format("SELECT id_spectrum AS id FROM " +
                                    "(SELECT id_spectrum, count(1::integer) as nSpeciesPerSpectrum " +
                                    "FROM {0}" +
                                    "WHERE {1} " +
                                    "GROUP BY id_spectrum) AS T " +
                                    "WHERE nSpeciesPerSpectrum >= {2} " 
                         , tiSP.SchemaTableName, cmd.CommandText, nPlants);
                } else {
                    cmd.CommandText = String.Format("SELECT id_spectrum FROM {0} WHERE {1} "
                         , tiSP.SchemaTableName, cmd.CommandText);
                }
            }
            return cmd;
        }

        
        private NpgsqlCommand sub_VEG_PS2() {
            NpgsqlCommand cmd = null;

            TableInfo ti_ps_view = DBM.getTableInfo("C_GFZ", "VIEW_SPEC2PLANT_SOCIETIES");
            TableInfo ti_ps_eunis = DBM.getTableInfo("CKEYS", "EUNIS_HABITATS");
            TableInfo ti_ps_bbl = DBM.getTableInfo("CKEYS", "GE_BIOTOPTYP_BB");
            TableInfo ti_ps_bfn = DBM.getTableInfo("CKEYS", "BFN_CODE");

            ConditionList cList = new ConditionList(ConditionList.Op.AND);
            cList.Add(FormHelper.getCondition(VGFZ_PS_EUNIS_DGV, "id", "eunis_id", Condition.Op.EQ));
            cList.Add(FormHelper.getCondition(VGFZ_PS_BB_DGV, "id", "biotoptyp_bb_id", Condition.Op.EQ));
            cList.Add(FormHelper.getCondition(VGFZ_PS_BfN_DGV, "code", "bfn_code", Condition.Op.EQ));

            if(!cList.IsEmpty) {
                cmd = cList.getCmd("veg_ps");
                cmd.CommandText = String.Format("SELECT id_spectrum FROM {0} WHERE {1}" 
                    , ti_ps_view.SchemaTableName, cmd.CommandText);
                
            }
            return cmd;
        }
        
        /// <summary>
        /// Checks if Object o is null, DBNull.value or an empty String
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        private bool isEmpty(Object o) {
            if (o == null || 
                o == DBNull.Value ||
                o.GetType() == typeof(DataRowView) ||
                o.ToString().Length == 0) return true;
                return false;
        }
        private bool isEmpty(NpgsqlCommand cmd) {
            return cmd.CommandText.Length == 0;
        }


        private NpgsqlCommand sub_OBSAREAS2() {
            NpgsqlCommand cmd = new NpgsqlCommand();
            Condition condition = FormHelper.getCondition(OBSAREA_DGV, "id", "id", Condition.Op.EQ);
            if(!condition.IsEmpty) {
                TableInfo ti_obsarea = DBM.getTableInfo("C_GFZ","VIEW_SPEC2OBSERVATION_AREAS");
                cmd = condition.getCmd("obsarea");
                cmd.CommandText = String.Format("SELECT id_spectrum FROM {0} WHERE {1}",
                   ti_obsarea.SchemaTableName, cmd.CommandText);
            }
            return cmd;
        }

       
        private NpgsqlCommand sub_LOCATION2() {
            NpgsqlCommand cmd = new NpgsqlCommand();
            ColumnInfoGeometry gi = (ColumnInfoGeometry)DBM.getColumnInfo("CORE", "LOCATIONS", "SHAPE");
            
            ConditionList clist = new ConditionList(ConditionList.Op.AND);
            if(LOC_name.Text.Trim().Length > 0) {
                if(LOC_matchAll.Checked){
                    clist.Add(new Condition("name", Condition.Op.LIKE, String.Format("%{0}%", LOC_name.Text)));
                }else{
                    clist.Add(new Condition("name", Condition.Op.LIKE, String.Format("{0}", LOC_name.Text)));
                }
            }

            String str_lo = LOC_LONG_X.Text;//;
            String str_la = LOC_LAT_Y.Text;//.Replace(',', '.');
            String str_bu = LOC_Buffer.Text;
            float lo, la, bu;
            if(float.TryParse(str_lo, out lo) &&
                float.TryParse(str_la, out la) &&
                float.TryParse(str_bu, out bu)) {

                GeometricCondition cond = new GeometricCondition(gi, GeometricCondition.Op.IS_WITHIN);
                cond.Add(lo, la, this.LOC_BUFFER_UC.SRID);
                cond.SetBuffer(bu);
                clist.Add(cond);
            }
            if(!clist.IsEmpty) {
                TableInfo ti_view_loc = this.DBM.getTableInfo("CORE", "LOCATIONS");
                cmd = clist.getCmd("loc");
                cmd.CommandText = String.Format("SELECT id FROM \"CORE\".\"SPECTRA\" WHERE id_location in (SELECT id FROM {0} WHERE {1})"
                        , ti_view_loc.SchemaTableName, cmd.CommandText);
            }
            return cmd;
        }
        

        #endregion

     
        private void VGFZ_SP_BtAdd_Click(object sender, EventArgs e) {
            FormHelper.setInfoFromSelectionTable(VGFZ_SP_DGV, true, DBM, "CKEYS", "GE_ARTEN_BUNDESLISTE", true, "Bitte Arten auswählen", "Selektierte Arten übernehmen");
            VGFZ_SP_DGV.AutoResizeColumns();
        }

        private void VGFZ_PS_BtAddBB_Click(object sender, EventArgs e) {
            FormHelper.setInfoFromSelectionTable(VGFZ_PS_BB_DGV, true,DBM, "CKEYS", "GE_BIOTOPTYP_BB", true, "Bitte Biotoptyp auswählen", "Selektierte Biotoptypen übernehmen");
            VGFZ_PS_BB_DGV.AutoResizeColumns();
        }
       
        private void OBSAREA_bt_Click(object sender, EventArgs e) {
            FormHelper.setInfoFromSelectionTable(OBSAREA_DGV, true, this.DBM, "C_GFZ", "VIEW_OBSERVATION_AREAS", true, "Bitte Beobachtungsfläche auswählen", "Fläche übernehmen");  
            OBSAREA_DGV.AutoResizeColumns();
        }
        private void VGFZ_PS_AddEUNIS_bt_Click(object sender, EventArgs e) {
            //Add rows from selection tableName
            FormHelper.setInfoFromSelectionTable(VGFZ_PS_EUNIS_DGV, true, this.DBM, "CKEYS", "EUNIS_HABITATS", true, "Bitte EUNIS Habitat auswählen", "Habitate übernehmen");
            VGFZ_PS_EUNIS_DGV.AutoResizeColumns();
            //VGFZ_PS_EUNIS_DGV.AutoResizeRows(DataGridViewAutoSizeRowsMode.AllCells);
            //VGFZ_PS_EUNIS_DGV.AutoSize = true;   
        }

        private void VGFZ_PS_AddBfN_bt_Click(object sender, EventArgs e) {
            FormHelper.setInfoFromSelectionTable(VGFZ_PS_BfN_DGV, true, this.DBM, "CKEYS", "BFN_CODE", true, "Bitte BfN Code auswählen", "Übernehmen");
            VGFZ_PS_BfN_DGV.AutoResizeColumns();

        }


        private void SEARCH_bt_Click(object sender, EventArgs e) {
            Val_Required(null, null);
            //SubSearchResults SSR = new SubSearchResults(this.search_cmd, this.cmd_Description, DBM.Connection, this.DBM);
            //SSR.Show();
            try {
                SubSearchResults SSN = new SubSearchResults(this.search_cmd, this.DBM);
                SSN.Show();
            } catch(Exception ex) { 
                String s = TextHelper.Exception2String(ex);
                FormHelper.ShowErrorBox(ex);
                this.RTB_CMD.Text += "\n"+s;
            }
        }

      
        private void EVENT_PrepareCommand(object sender, EventArgs e) {
            Val_Required(null, null);
        }

        private void uC_ParseNumbers1_LabelsChanged(object sender, EventArgs e) {
            Val_Required(null, null);
        }

        private void CORE_Date_Begin_ValueChanged(object sender, EventArgs e) {
            Val_Required(null, null);
        }

        private void CORE_Date_End_ValueChanged(object sender, EventArgs e) {
            Val_Required(null, null);
        }

        private void CORE_Date_End_Validating(object sender, CancelEventArgs e) {
            
        }

        private void VGFZ_PS_RemoveRowBB_bt_Click(object sender, EventArgs e) {
            FormHelper.removeSelectedRows(VGFZ_PS_BB_DGV);
        }

        private void gb_CGFZ_OBSAREA_removeRow_bt_Click(object sender, EventArgs e) {
            FormHelper.removeSelectedRows(OBSAREA_DGV);
        }

        private void VGFZ_PS_RemoveRowBfN_bt_Click(object sender, EventArgs e) {
            FormHelper.removeSelectedRows(VGFZ_PS_BfN_DGV);
        }

        private void VGFZ_PS_RemoveRowEUNIS_bt_Click(object sender, EventArgs e) {
            FormHelper.removeSelectedRows(VGFZ_PS_EUNIS_DGV);
        }

        private void VGFZ_SP_BtRemove_Click(object sender, EventArgs e) {
            FormHelper.removeSelectedRows(VGFZ_SP_DGV);
        }

        private void OBSAREA_DGV_SelectionChanged(object sender, EventArgs e) {
            gb_CGFZ_OBSAREA_removeRow_bt.Enabled = OBSAREA_DGV.SelectedRows.Count > 0;
        }

        private void VGFZ_PS_BB_DGV_SelectionChanged(object sender, EventArgs e) {
            VGFZ_PS_RemoveRowBB_bt.Enabled  = VGFZ_PS_BB_DGV.SelectedRows.Count > 0;
        }

        private void VGFZ_SP_DGV_SelectionChanged(object sender, EventArgs e) {
            VGFZ_SP_BtRemove.Enabled = VGFZ_SP_DGV.SelectedRows.Count > 0;
        }

        private void VGFZ_PS_EUNIS_DGV_SelectionChanged(object sender, EventArgs e) {
            VGFZ_PS_RemoveRowEUNIS_bt.Enabled = VGFZ_PS_EUNIS_DGV.SelectedRows.Count > 0;
        }

        private void VGFZ_PS_BfN_DGV_SelectionChanged(object sender, EventArgs e) {
            VGFZ_PS_RemoveRowBfN_bt.Enabled = VGFZ_PS_BfN_DGV.SelectedRows.Count > 0;
        }

        
    }




}
